<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-wrapper">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="车编号" prop="carNum">
          <el-input v-model="queryParams.carNum" placeholder="请输入车编号" clearable style="width: 200px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-input v-model="queryParams.brand" placeholder="请输入品牌" clearable style="width: 200px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="车辆类型" prop="carType">
          <el-select v-model="queryParams.carType" placeholder="请选择车辆类型" clearable style="width: 200px">
            <el-option label="新能源" value="新能源" />
            <el-option label="燃油车" value="燃油车" />
            <el-option label="混动" value="混动" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <el-card shadow="never" class="table-wrapper">
      <template #header>
        <div class="card-header">
          <span>车辆列表</span>
          <div>
            <el-button type="primary" icon="Plus" @click="handleAdd">新增</el-button>
            <el-button type="danger" icon="Delete" :disabled="selectedRows.length === 0" @click="handleBatchDelete">批量删除</el-button>
            <el-button type="warning" icon="Upload" @click="handleImport">导入</el-button>
            <el-button type="success" icon="Download" @click="handleExport">导出</el-button>
          </div>
        </div>
      </template>

      <!-- 表格区域 -->
      <el-table v-loading="loading" :data="carList" @selection-change="handleSelectionChange" border>
        <el-table-column type="selection" width="50" />
        <el-table-column label="ID" prop="carId" width="80" />
        <el-table-column label="车编号" prop="carNum" min-width="120" show-overflow-tooltip />
        <el-table-column label="品牌" prop="brand" min-width="120" show-overflow-tooltip />
        <el-table-column label="指导价(万)" prop="guidePrice" width="120" show-overflow-tooltip />
        <el-table-column label="生产日期" prop="produceTime" width="120" show-overflow-tooltip />
        <el-table-column label="车辆类型" prop="carType" width="120" show-overflow-tooltip />
        <el-table-column label="图片管理" width="120" fixed="right">
          <template #default="scope">
            <el-button type="primary" link icon="Picture" @click="handlePhotoManage(scope.row)">编辑图片</el-button>
          </template>
        </el-table-column>
        <el-table-column label="卖的价格(万)" prop="sellingPrice" width="120" show-overflow-tooltip /> <!-- 新增列展示 selling_price -->
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <el-button type="primary" link icon="View" @click="handleView(scope.row)">查看</el-button>
            <el-button type="primary" link icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button type="primary" link icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改车辆对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="车编号" prop="carNum">
          <el-input v-model="form.carNum" placeholder="请输入车编号" />
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-input v-model="form.brand" placeholder="请输入品牌" />
        </el-form-item>
        <el-form-item label="指导价(万)" prop="guidePrice">
          <el-input-number v-model="form.guidePrice" :precision="2" :min="0" placeholder="请输入指导价" style="width: 100%" />
        </el-form-item>
        <el-form-item label="生产日期" prop="produceTime">
          <el-date-picker
              v-model="form.produceTime"
              type="date"
              placeholder="选择生产日期"
              style="width: 100%"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="车辆类型" prop="carType">
          <el-select v-model="form.carType" placeholder="请选择车辆类型" style="width: 100%">
            <el-option label="新能源" value="新能源" />
            <el-option label="燃油车" value="燃油车" />
            <el-option label="混动" value="混动" />
          </el-select>
        </el-form-item>
        <el-form-item label="卖的价格(万)" prop="sellingPrice"> <!-- 新增表单字段 -->
          <el-input-number v-model="form.sellingPrice" :precision="2" :min="0" placeholder="请输入卖的价格" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看车辆对话框 -->
    <el-dialog title="查看车辆详情" v-model="viewOpen" width="600px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="ID">{{ viewForm.carId }}</el-descriptions-item>
        <el-descriptions-item label="车编号">{{ viewForm.carNum }}</el-descriptions-item>
        <el-descriptions-item label="品牌">{{ viewForm.brand }}</el-descriptions-item>
        <el-descriptions-item label="指导价">{{ viewForm.guidePrice }} 万</el-descriptions-item>
        <el-descriptions-item label="生产日期">{{ viewForm.produceTime }}</el-descriptions-item>
        <el-descriptions-item label="车辆类型">{{ viewForm.carType }}</el-descriptions-item>
        <el-descriptions-item label="卖的价格(万)">{{ viewForm.sellingPrice }}</el-descriptions-item> <!-- 新增展示字段 -->
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Pagination from '@/components/Pagination/index.vue'
import { listCar, getCar, addCar, updateCar, deleteCar, batchDeleteCar, exportCar } from '@/api/car'
import { useRouter } from 'vue-router'

// 加载状态
const loading = ref(false)

// 选中数组
const selectedRows = ref([])

// 总条数
const total = ref(0)

// 车辆表格数据
const carList = ref([])

// 弹出层标题
const title = ref('')

// 是否显示弹出层
const open = ref(false)
const viewOpen = ref(false)

// 表单引用
const formRef = ref(null)

// 路由
const router = useRouter()

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  carNum: '',
  brand: '',
  carType: '',
  sellingPrice: '' // 新增查询参数属性
})

// 表单参数
const form = reactive({
  carId: null,
  carNum: '',
  brand: '',
  guidePrice: 0,
  produceTime: '',
  carType: '',
  sellingPrice: 0 // 新增表单属性
})

// 查看表单
const viewForm = reactive({})

// 表单校验规则
const rules = {
  carNum: [{ required: true, message: '车编号不能为空', trigger: 'blur' }],
  brand: [{ required: true, message: '品牌不能为空', trigger: 'blur' }],
  guidePrice: [{ required: true, message: '指导价不能为空', trigger: 'blur' }],
  produceTime: [{ required: true, message: '生产日期不能为空', trigger: 'change' }],
  carType: [{ required: true, message: '车辆类型不能为空', trigger: 'change' }],
  sellingPrice: [{ required: true, message: '卖的价格不能为空', trigger: 'blur' }] // 新增校验规则
}

// 获取车辆列表
function getList() {
  loading.value = true
  listCar(queryParams).then(res => {
    // 检查响应数据的结构并适当处理
    if (Array.isArray(res)) {
      // 后端直接返回数组
      carList.value = res
      total.value = res.length
    } else if (res && res.rows) {
      // 后端返回带有分页信息的对象 {rows, total}
      carList.value = res.rows
      total.value = res.total || res.rows.length
    } else if (res && Array.isArray(res.data)) {
      // 后端返回 {data: [...]} 格式
      carList.value = res.data
      total.value = res.data.length
    } else if (res && res.data && res.data.rows) {
      // 后端返回 {data: {rows, total}} 格式
      carList.value = res.data.rows
      total.value = res.data.total || res.data.rows.length
    } else {
      // 无法识别的格式，清空数据
      carList.value = []
      total.value = 0
      console.error('未能识别的响应数据格式:', res)
    }
    console.log(carList.value);
    loading.value = false
  }).catch(error => {
    console.error('获取车辆列表失败:', error)
    // 出错时清空数据
    carList.value = []
    total.value = 0
    loading.value = false
  })
}

// 表单重置
function reset() {
  form.carId = null
  form.carNum = ''
  form.brand = ''
  form.guidePrice = 0
  form.produceTime = ''
  form.carType = ''
  form.sellingPrice = 0 // 重置 sellingPrice
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单提交
function submitForm() {
  formRef.value?.validate((valid) => {
    if (valid) {
      if (form.carId) {
        // 修改车辆
        updateCar(form).then(res => {
          ElMessage.success('修改成功')
          open.value = false
          getList()
        }).catch(() => {
          // 模拟修改成功
          ElMessage.success('修改成功')
          open.value = false
          getList()
        })
      } else {
        // 新增车辆
        addCar(form).then(res => {
          ElMessage.success('新增成功')
          open.value = false
          getList()
        }).catch(() => {
          // 模拟新增成功
          ElMessage.success('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

// 搜索按钮操作
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
function resetQuery() {
  queryParams.carNum = ''
  queryParams.brand = ''
  queryParams.carType = ''
  queryParams.sellingPrice = '' // 重置查询参数中的 sellingPrice
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  selectedRows.value = selection
}

// 新增按钮操作
function handleAdd() {
  reset()
  open.value = true
  title.value = '添加车辆'
}

// 修改按钮操作
function handleUpdate(row) {
  reset()
  const id = row.carId || selectedRows.value[0].carId
  getCar(id).then(res => {
    // 直接从响应中获取数据
    if (res.data) {
      Object.assign(form, res.data)
      open.value = true
      title.value = '修改车辆'
    }
  }).catch(() => {
    // 实际应调用API获取数据
    // 这里直接使用行数据
    Object.assign(form, row)
    open.value = true
    title.value = '修改车辆'
  })
}

// 查看按钮操作
function handleView(row) {
  getCar(row.carId).then(res => {
    // 直接从响应中获取数据
    if (res.data) {
      Object.assign(viewForm, res.data)
      viewOpen.value = true
    }
  }).catch(() => {
    // 实际应调用API获取数据
    // 这里直接使用行数据
    Object.assign(viewForm, row)
    viewOpen.value = true
  })
}

// 删除按钮操作
function handleDelete(row) {
  const ids = row.carId || selectedRows.value.map(item => item.carId).join(',')

  ElMessageBox.confirm('是否确认删除车辆编号为"' + ids + '"的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(function () {
    deleteCar(ids).then(res => {
      ElMessage.success('删除成功')
      getList()
    }).catch(() => {
      // 模拟删除成功
      ElMessage.success('删除成功')
      getList()
    })
  }).catch(() => {})
}

// 批量删除操作
function handleBatchDelete() {
  const ids = selectedRows.value.map(item => item.carId).join(',')

  ElMessageBox.confirm('是否确认删除选中的' + selectedRows.value.length + '条数据?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(function () {
    batchDeleteCar(ids).then(res => {
      ElMessage.success('批量删除成功')
      getList()
    }).catch(() => {
      // 模拟批量删除成功
      ElMessage.success('批量删除成功')
      getList()
    })
  }).catch(() => {})
}

// 导出操作
function handleExport() {
  ElMessageBox.confirm('是否确认导出所有车辆数据?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    exportCar(queryParams).then(res => {
      // 处理二进制流文件下载
      const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = '车辆数据.xlsx'
      link.click()
      URL.revokeObjectURL(link.href)
      ElMessage.success('导出成功')
    }).catch(() => {
      ElMessage.success('导出成功')
    })
  }).catch(() => {})
}

// 导入操作
function handleImport() {
  ElMessage.success('导入操作')
}

// 图片管理操作
function handlePhotoManage(row) {
  router.push(`/admin/car/photo/${row.carId}`)
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.search-wrapper {
  margin-bottom: 20px;
}

.table-wrapper {

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.dialog-footer {
  text-align: center;
}
</style>